package com.example.demo.leetcode.classics150;

import java.util.PriorityQueue;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _124数据流的中位数
 * @description
 * @date 2023/08/18 14:57
 * <p>
 * ******************************************************
 */
public class _124数据流的中位数 {

    private PriorityQueue<Integer> min;
    private PriorityQueue<Integer> max;

    public _124数据流的中位数() {
        min = new PriorityQueue<>();
        max = new PriorityQueue<>((a, b) -> b - a);
    }

    public void addNum(int num) {
        if (min.size() >= max.size()) {
            min.offer(num);
            max.offer(min.poll());
        } else {
            max.offer(num);
            min.offer(max.poll());
        }
    }

    public double findMedian() {
        if (min.isEmpty() && max.isEmpty()) {
            return 0.0;
        }
        if (min.size() == max.size()) {
            return ((double) min.peek() + (double) max.peek()) / 2;
        }
        return min.size() > max.size() ? min.peek() : max.peek();
    }

    public static void main(String[] args) {
        _124数据流的中位数 s = new _124数据流的中位数();
        s.addNum(-1);
        s.addNum(-2);
        s.addNum(-3);
        s.addNum(-4);
        s.addNum(-5);
        System.out.println(s.findMedian());
    }
}
